<?php

namespace Controller;

use \Daiyong\File as file;

class Common {
    public $config = array();
    public $db = array();
    public $ciphertext = '34&^u!@#s'; //密文(手机验证码加密)
    public function __construct() {
        global $_CONFIG;
        //全局配置赋值
        $this->config = $_CONFIG;
        //将get与POST参数全部trim
        if (isset($_GET))  $_GET = $this->trimArray($_GET);
        if (isset($_POST))  $_POST = $this->trimArray($_POST);
    }
    /**
     * @description: 排序解析
     * @param {*} $keys 传入允许排序的数据库字段
     * @return {*} order by id asc
     */
    public function sqlOrderBy($keys) {
        if (
            in_array(@$_GET['sort_key'], $keys) &&
            in_array(@$_GET['sort_val'], ['asc', 'desc'])
        ) {
            return 'order by ' . $_GET['sort_key'] . ' ' . $_GET['sort_val'];
        }
        return '';
    }
    public function sqlLimit() {
        $begin = (int)$_GET['begin'];
        $size = (int)$_GET['size'];
        if ($begin < 0) $begin = 0;
        if ($size <= 0) $size = $this->config['page']['limitDefault'];
        if ($size > $this->config['page']['limitMax'])  $size = $this->config['page']['limitMax'];
        return 'limit ' . $begin . ',' . $size;
    }
    /**
     * @description: 下载文件
     * @param {*} $path 文件路径
     * @param {*} $fileName 文件名称
     * @return {*}
     */
    public function download($path, $fileName = '') {
        //检查文件与下载
        $filePath = file::path($path);
        if (!file_exists($filePath)) {
            $this->error('未找到下载内容');
        }
        //获取文件信息
        if (!$fileName) $fileName = basename($filePath);
        //设置头信息
        header('Content-Disposition: attachment; filename="' . $fileName . '"');
        header('Content-Type: application/octet-stream');
        header('Content-Length: ' . filesize($filePath));
        // 打开文件以二进制方式输出
        $chunkSize = 1024 * 1024; // 1MB
        $handle  = fopen($filePath, 'rb');
        while (!feof($handle)) {
            echo fread($handle, $chunkSize);
            ob_flush();
            flush();
        }
        fclose($handle);
        exit();
    }
    //输出
    public function result($status, $message1 = '成功', $message2 = '失败') {
        if ($status)  $this->success($message1);
        else $this->error($message2);
    }
    public function success($data = array(), $message = '成功') {
        $this->echo(1, $message, $data);
    }
    public function error($data = array(), $message = '失败') {
        $this->echo(0,  $message, $data);
    }
    //输出多条结果
    // $list[] = array(
    //     'key' => $v,
    //     'option' => '删除',
    //     'return' => $this->model->delete(['id' => $v])
    // );
    public function resultArray($list) {
        $message = array();
        foreach ($list as $v) {
            if (is_array($v['return'])) {
                $message[] = array(
                    'status' => 0,
                    'message' => $v['key'] . ' ' . $v['return']['message']
                );
            } else {
                if ($v['return']) {
                    $message[] = array(
                        'status' => 1,
                        'message' =>  $v['key'] . ' ' . $v['option'] . '成功'
                    );
                } else {
                    $message[] = array(
                        'status' => 0,
                        'message' =>  $v['key'] . ' ' . $v['option'] . '失败'
                    );
                }
            }
        }
        if (count($message) == 1) {
            $message[0]['message'] = substr($message[0]['message'], strlen($list[0]['key'] . ' '), strlen($message[0]['message']));
            $this->echo($message[0]['status'], $message[0]['message']);
        } else {
            $this->echo(3, $message);
        }
    }
    public function echo($status, $message, $data = array()) {
        if (!is_array($data)) {
            $message = $data;
            $data = array();
        }
        echo json_encode(array(
            'status' => $status,
            'message' => $message,
            'data' => $data
        ));
        exit();
    }
    //将数组里面的值全部trim
    private function trimArray($array) {
        if (is_array($array)) {
            foreach ($array as &$v) {
                $v = $this->trimArray($v);
            }
            return $array;
        } elseif (is_string($array)) {
            return trim($array);
        }
    }
}
